<script lang="tsx">
import { defineComponent, ref, provide } from "vue"
import { collapseProps } from "./props"

export default defineComponent({
	name: "ChenCollapse",
	props: collapseProps,
	emits: ["change", "update:modelValue"],
	setup(props, { slots, emit }) {
		// 1.拿到用户传递的已打开面板数组
		const activeNames = ref(props.modelValue)
		// 2.collapse核心方法 - itemName用户点击的项目name值 - 并将provide提供给子组件
		const handleItemClick = (itemName: string) => {
			let _activeNames = [...activeNames.value]
			// 针对该数组进行操作
			if (props.accordion) {
				// 手风琴模式
				_activeNames = [activeNames.value[0] === itemName ? "" : itemName]
			} else {
				// 普通折叠面板-可打开多个
				const index = _activeNames.indexOf(itemName)
				if (index > -1) {
					// 面板在数组中
					_activeNames.splice(index, 1)
				} else {
					_activeNames.push(itemName)
				}
			}
			// 无论什么模式，都准备好了最新数组
			activeNames.value = _activeNames
			// 接下来触发两个事件
			emit("update:modelValue", _activeNames)
			emit("change", _activeNames)
		}
		provide(Symbol.for("itemClick"), handleItemClick)
		provide(Symbol.for("activeNames"), activeNames)
		return () => <div class="collapse-container">{slots.default ? slots.default() : null}</div>
	},
})
</script>

<style lang="less" scoped>
.collapse-container {
	border-top: 1px solid var(--chen-border-color);
	border-bottom: 1px solid var(--chen-border-color);
}
</style>
